<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="view-table">
      <template #high_form="{ form }">
        <XForm ref="form" :fieldList="highFieldList" :options="formOption" labelPosition="top" :formData="form" :originOption="originOption" class="grid grid-cols-3"> </XForm>
      </template>

      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow"> </XForm>
      </template>
      <template #toolbar_btns>
        <!-- <el-button type="primary" @click="onOperatorReview('SUBMIT')">批量提交</el-button>
        <el-button type="primary" @click="onOperatorReview('CONFIRMED')">运营通过</el-button>
        <el-button type="primary" @click="onOperatorReview('REJECTED')">运营驳回</el-button>
        <el-button type="primary" @click="createIntelligent">批量生成备货计划</el-button>
        <el-button type="primary" @click="openConfirmInput('batchEdit')">批量修改</el-button>
        <el-button type="danger" @click="onOperatorReview('CANCEL')">作废</el-button>
        <el-button type="primary" @click="onCopy">复制</el-button>
        <el-button type="danger" @click="onOperatorReview('ROLLBACK')">反审</el-button> -->

        <VButton auth="/pmc/plan/unconfirmed/submit" type="primary" @click="onOperatorReview('SUBMIT')"> 批量提交 </VButton>
        <VButton auth="/pmc/plan/unconfirmed/confirmed" type="primary" @click="onOperatorReview('CONFIRMED')"> 运营通过 </VButton>
        <VButton auth="/pmc/plan/unconfirmed/rejected" type="primary" @click="onOperatorReview('REJECTED')"> 运营驳回 </VButton>
        <VButton auth="/pmc/plan/unconfirmed/createIntelligent" type="primary" @click="createIntelligent"> 批量生成备货计划 </VButton>
        <VButton auth="/pmc/plan/unconfirmed/batchUpdate" type="primary" @click="openConfirmInput('batchEdit')"> 批量修改 </VButton>
        <VButton auth="/pmc/plan/unconfirmed/cancel" type="danger" @click="onOperatorReview('CANCEL')"> 作废 </VButton>
        <VButton auth="/pmc/plan/unconfirmed/copy" type="primary" @click="onCopy"> 复制 </VButton>
        <VButton auth="/pmc/plan/unconfirmed/rollback" type="danger" @click="onOperatorReview('ROLLBACK')"> 反审 </VButton>

        <div class="w-[100%] mt-[12px]">
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane v-for="item in statusOpt" :key="item.operator_review_status" :name="item.operator_review_status" :label="`${item.operator_review_status_text}(${item.count})`" />
          </el-tabs>
        </div>
      </template>
    </VTable>

    <!-- ASIN销量趋势 -->
    <AsinSalesTrend ref="AsinSalesTrendRef" />

    <!-- 弹窗 表单编辑 -->
    <ConfirmInput v-model="batchVisible" v-bind="currentConfirm" @submit="handleConfirmSubmit" />

    <!-- 日志 -->
    <XLog ref="logRef" :api="planSpaLog" />
  </VPage>
</template>

<script setup lang="jsx">
import { planSpaLog } from "@/api/plan"
import { reviewStatusStatistics, unconfirmedList, operatorReview, updateUnconfirmedSpa, intelligentCreate, spaCopy, recordPushPms } from "./api.js"

import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"

import XForm from "@/components/XForm/index.vue"
// 弹窗 表单编辑
import ConfirmInput from "@/components/ConfirmInput/index.vue"
// 日志
import XLog from "@/components/XLog"
const logRef = ref()

// ASIN销量趋势
import AsinSalesTrend from "@/views/plan/components/AsinSalesTrend/index.vue"
const AsinSalesTrendRef = ref()

const tableRef = ref()

const activeName = ref("")
const statusOpt = ref([])
const handleClick = () => {
  query()
}

const onOperatorReview = (review_type = "", row = false) => {
  let params = { review_type }
  let length = 0
  if (row) {
    // 操作行
    length = 1
    params.id = [row.id]
  } else {
    // 批量操作
    let rows = tableRef?.value.$table.getCheckboxRecords()
    if (!rows.length) {
      return ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    }
    length = rows.length
    params.id = rows.map((v) => v.id)
  }
  if (review_type == "REJECTED") {
    // 驳回
    openConfirmInput("reject", params)
  } else {
    if (row) {
      // 操作行
      handleSave(params)
    } else {
      // 批量操作
      ElMessageBox.confirm(`操作${length}条数据, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "pmc-message-confirm-button",
      }).then(async () => {
        try {
          handleSave(params)
        } catch (e) {
          throw Error(e)
        }
      })
    }
  }
}
const onCopy = () => {
  let rows = tableRef?.value.$table.getCheckboxRecords()
  if (!rows.length) {
    return ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
  }
  ElMessageBox.confirm(`此操作复制${rows.length}条数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "pmc-message-confirm-button",
  }).then(async () => {
    try {
      spaCopy({ id: rows.map((v) => v.id) }).then((res) => {
        query()
        ElMessage({ type: "success", message: "操作成功" })
      })
    } catch (e) {
      throw Error(e)
    }
  })
}
const createIntelligent = () => {
  let rows = tableRef?.value.$table.getCheckboxRecords()
  if (!rows.length) {
    return ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
  }
  console.log(rows)
  recordPushPms({ id: rows.map((v) => v.id) }).then(async (res) => {
    if (res.data.fail_message) {
      // ElMessage({ type: "warning", message: res.data.fail_message })
      ElMessageBox.confirm(res.data.fail_message, "提示", {
        showConfirmButton: false,
        cancelButtonText: "关闭",
        type: "warning",
        customClass: "my-message",
      })
    } else {
      ElMessage({ type: "success", message: res.message })
    }
    query()
  })
  // let params = {
  //   data: rows.map((v) => ({
  //     platform: v.platform_id,
  //     demand_type: 2,
  //     country: v.site_code,
  //     sale_id: v.operator_user,
  //     sku: v.sku,
  //     asin: v.asin,
  //     // destination_warehouse: v.ccc,
  //     transport_type: v.spa_lt_days?.transportation_type,
  //     demand_num: v.spa_analysis?.stocking_quantity,
  //     // demand_time: parseTime(new Date(), "{y}-{m}-{d}"),
  //     // ow?.estimated_shipping_time?.split(" ")[0]
  //     demand_time: v.estimated_shipping_time?.split(" ")[0],
  //     remark: v.remarks || "",
  //     relation_no: v.plan_no,
  //     order_source: 3,
  //   })),
  // }
  // intelligentCreate(params).then(async (res) => {
  //   if (res.data?.fail_message) {
  //     ElMessage({ type: "warning", message: res.data.fail_message })
  //   } else {
  //     let { data } = await recordPushPms({ id: rows.map((v) => v.id) })
  //     ElMessage({ type: "success", message: data.fail_message })
  //   }
  //   query()
  // })
}
// 保存
const handleSave = (params) => {
  operatorReview(params).then((res) => {
    query()
    ElMessage({ type: "success", message: "操作成功" })
  })
}
import { parseTime } from "@/utils/ruoyi"
const data = reactive({
  batchVisible: false,
  currentConfirm: {},
})
const { batchVisible, currentConfirm } = toRefs(data)
const handleConfirmSubmit = async (param) => {
  let requests = null
  let params = {}
  switch (currentConfirm.value.type) {
    // 运营驳回
    case "reject":
      requests = operatorReview
      params = param
      break
    // 编辑
    case "edit":
      requests = updateUnconfirmedSpa
      params = param
      break
    default:
      break
  }

  await requests(params).then((res) => {
    ElMessage.success(res.message)
    query()
  })
  batchVisible.value = false
  currentConfirm.value = {}
}

const openConfirmInput = (type, param) => {
  let confirmOpt = {}
  console.log(type)

  switch (type) {
    // 运营驳回
    case "reject":
      confirmOpt = currentConfirmOpt.reject
      confirmOpt.form = param
      break
    // 修改
    case "edit":
      confirmOpt = currentConfirmOpt.edit
      confirmOpt.form = {
        id: param.id,
        estimated_shipping_time: parseTime(param.estimated_shipping_time, "{y}-{m}-{d}"),
        stocking_quantity: param.stocking_quantity,
        transportation_type: param.transportation_type,
        remark: param.remark,
      }
      confirmOpt.originOption = originOption.value
      break

    case "batchEdit":
      console.log(1909199)

      // console.log(1);

      return
      // confirmOpt = currentConfirmOpt.edit
      // confirmOpt.form = {
      //   id: param.id,
      //   estimated_shipping_time: parseTime(param.estimated_shipping_time, "{y}-{m}-{d}"),
      //   stocking_quantity: param.stocking_quantity,
      //   transportation_type: param.transportation_type,
      //   remark: param.remark,
      // }
      // confirmOpt.originOption = originOption.value
      break

    default:
      break
  }
  console.log(3333)

  confirmOpt.type = type
  // console.log(confirmOpt)
  currentConfirm.value = confirmOpt
  batchVisible.value = true
}

const currentConfirmOpt = {
  // 运营驳回
  reject: {
    title: "运营驳回",
    form: {},
    fieldOptions: [
      {
        label: "驳回备注",
        field: "reject_reason",
        type: "textarea",
        options: { placeholder: "驳回备注" },
        autosize: { minRows: 2, maxRows: 6 },
        style: { width: "100%" },
      },
    ],
    rules: { reject_reason: [{ required: true, message: "请选择", trigger: "change" }] },
  },
  // 编辑
  edit: {
    title: "修改",
    form: {},
    fieldOptions: [
      {
        label: "需求数",
        field: "stocking_quantity",
        options: { placeholder: "需求数" },
        style: { width: "100%" },
      },
      {
        label: "运输类型",
        field: "transportation_type",
        type: "select",
        originField: "Base.BaseAsinList.TransportationTypeEnum",
        options: { placeholder: "运输类型" },
        style: { width: "100%" },
      },
      {
        label: "预计发货时间",
        field: "estimated_shipping_time",
        type: "dateTimeRangeNorm",
        itemProps: {
          type: "date",
          shortcuts: [],
          format: "YYYY-MM-DD",
          valueFormat: "YYYY-MM-DD",
        },

        style: { width: "100%" },
      },
      {
        label: "备注",
        field: "remark",
        type: "textarea",
        options: { placeholder: "备注" },
        autosize: { minRows: 2, maxRows: 6 },
        style: { width: "100%" },
      },
    ],
    rules: {
      // stocking_quantity: [{ required: true, message: "请选择", trigger: "blur" }],
      // transportation_type: [{ required: true, message: "请选择", trigger: "change" }],
      // estimated_shipping_time: [{ required: true, message: "请选择", trigger: "change" }],
      // remark: [{ required: true, message: "请选择", trigger: "blur" }],
    },
  },
}

// 查询
const query = () => {
  tableRef?.value.query()
}

const formShow = ref(false)
//获取下拉数据
onMounted(async () => {
  getOption()
  nextTick(() => {
    formShow.value = true
  })
})

// 枚举 数据
const originOption = ref({})
// import { enumGet, enumOptions } from "@/api"
import { getSupplie } from "@/api"
import { getEnum } from "@/utils/enumUtils"
// 获取下拉数据
const getOption = async () => {
  let keys = ["Plan.PlanSpa.OperatorReviewStatusEnum", "Plan.PlanStockingPlan.TypeEnum", "Base.BaseAsinList.TransportationTypeEnum"]
  const data = await getEnum(keys)

  keys.forEach((key) => {
    originOption.value[key] = data[key]
  })
  let enumKey = ["amazonSite", "goods_active"]
  const enumData = await getEnum(enumKey, "enumOptions")
  enumKey.forEach((key) => {
    originOption.value[key] = enumData[key]
  })
  originOption.value.supplier = (await getSupplie())?.data
}

const formOption = ref({ inline: true })
import {
  fieldList, // 搜索条件 配置
  highFieldList,
} from "./config.jsx"
const countryFlag = {
  uk: "gb",
}
const getFlag = (country) => {
  return countryFlag[country] || country
}

const statusColor = {
  0: "text-[blue]",
  2: "text-[green]",
  4: "text-[red]",
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      operator_review_status: "",
      skuRange: { type: "sku", value: "" },
      timeRange: { type: "created_at", value: "", range: true },
    },
  },
  rowConfig: { height: 158 },
  showOverflow: false,
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },

    {
      title: "备货计划信息",
      width: 240,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="计划单号" value={row.plan_no} line={1} class="font-bold" />
            <VText title="计划类型" value={row.stocking_plan?.plan_type_text} line={1} />
            <VText title="需求部门" value={row?.department_name} line={1} />
            <VText title="计划人员" value={row.stocking_plan?.created_by_text} line={1} />
            <VText title="目的仓" value={row.warehouse_name} line={1} />
            <VText title="创建时间" value={row.created_at} line={1} />
            <VText title="PR单号" value={row.pr_no} line={1} />
          </div>
        ),
      },
    },

    {
      title: "销售信息",
      width: 200,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center mb-[8px] font-bold">
              <span>{row.site_code}</span>
              <country-flag country={getFlag(row?.site_code?.toLowerCase())} class="ml-[16px]" size="big" shadow />
            </div>
            <VText title="销售" value={row.operator_user_text} line={1} class="font-bold" />
            <VText value={row.department_name} line={99} />
          </div>
        ),
      },
    },

    {
      title: "商品信息",
      width: 260,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="flex items-center">
              <div class="flex-1">
                <div class={`${statusColor[row.operator_review_status]} font-bold`}>{row.operator_review_status_text}</div>
                <VText title="SKU" value={row.sku} line={1} class="font-bold" />
                <VText title="ASIN" value={row.asin} line={1} class="font-bold" />
                <VText title="活跃度" value={row.activity_status_text} line={1} class={activityColor[row.activity_status_text] || ""} class="font-bold" />
              </div>
              <div>
                <el-image style="width:80px;height:80px" src={row.sku_attr_img} />
              </div>
            </div>
            <VText value={row.sku_title} line={2} class="font-bold" />
          </div>
        ),
      },
    },

    {
      title: "备货数量/金额",
      width: 140,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="总数量" value={row.spa_analysis?.stocking_quantity} line={1} class="font-bold" />
            <VText title="总金额CNY" value={row.spa_analysis?.total_amount} line={1} class="font-bold" />
          </div>
        ),
      },
    },

    {
      title: "发货方式",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <VText title="运输类型" value={row.plan_spa_lt_days?.transportation_type_text} line={1} />
            <VText title="运输天数" value={row.spa_lt_days?.transportation_days} line={1} />
            <VText title="预计发货" value={row?.estimated_shipping_time?.split(" ")[0]} line={1} class="font-bold" />
          </div>
        ),
      },
    },

    {
      title: "库存可售天数",
      width: 180,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="font-bold">{row.spa_inventory_availability?.total_inventory_days} 天</div>

            <VText title="FBA可售" value={row.spa_inventory_availability?.fba_sellable_days ? row.spa_inventory_availability?.fba_sellable_days + "天" : ""} line={1} />
            <VText title="FBA在途" value={row.spa_inventory_availability.fba_in_transit_days ? row.spa_inventory_availability.fba_in_transit_days + "天" : ""} line={1} />
            <VText
              title="海外仓在途"
              value={row.spa_inventory_availability.overseas_warehouse_in_transit_days ? row.spa_inventory_availability.overseas_warehouse_in_transit_days + "天" : ""}
              line={1}
            />
            <VText
              title="海外仓可用"
              value={row.spa_inventory_availability.overseas_warehouse_available_days ? row.spa_inventory_availability.overseas_warehouse_available_days + "天" : ""}
              line={1}
            />
          </div>
        ),
      },
    },

    {
      title: "库存信息",
      width: 220,
      slots: {
        default: ({ row }) => (
          <div class="grid grid-cols-2 gap-x-2">
            <VText title="FBA可用" value={row.spa_inventory.fba_available} line={1} />
            <VText title="本地仓可用" value={row.spa_inventory.local_warehouse_available} line={1} />
            <VText title="本地仓待发" value={row.spa_inventory.local_warehouse_pending_shipment} line={1} />
            <VText title="海外仓可用" value={row.spa_inventory.overseas_warehouse_available} line={1} />
            <VText title="采购在途" value={row.spa_inventory.procurement_in_transit} line={1} />
            <VText title="FBA在途" value={row.spa_inventory.fba_in_transit} line={1} />
            <VText title="海外仓在途" value={row.spa_inventory.overseas_transit_in_transit} line={1} />
          </div>
        ),
      },
    },

    {
      title: "销量信息",
      width: 160,
      slots: {
        default: ({ row }) => (
          <div class="grid grid-cols-2">
            <VText title="7天" value={row?.spa_sales.sales_num_seven_days} line={1} />
            <VText title="14天" value={row?.spa_sales.sales_num_fourteen_days} line={1} />
            <VText title="30天" value={row?.spa_sales.sales_num_thirty_days} line={1} />
            <VText title="90天" value={row?.spa_sales.sales_num_ninety_days} line={1} />
            <svg-icon icon-class="tubiao" class="text-[#3487ff] text-[1.5em]" onClick={() => AsinSalesTrendRef.value.open(row.base_asin_id)} />
          </div>
        ),
      },
    },

    {
      title: "采购信息",
      width: 240,
      slots: {
        default: ({ row }) => (
          <div>
            <div class="grid grid-cols-2">
              <VText title="采购价" value={row.spa_purchases?.purchase_price} line={1} />
              <div>
                <el-divider direction="vertical" />
                {row.spa_purchases?.min_order_quantity}起批
              </div>
            </div>
            <VText title="采购天数" value={row.spa_purchases?.purchase_days} line={1} />
            <VText title="单箱数量" value={row.spa_purchases?.mpq_min_quantity} line={1} />
            <VText title="供应商" value={row.spa_purchases?.supplier_name} line={1} />

            <VText title="采购人员" value={row.purchaser_user_text} line={1} />
            <VText title="开发人员" value={row.operator_user_text} line={1} />
          </div>
        ),
      },
    },

    {
      title: "运营驳回原因",
      width: 180,
      slots: {
        default: ({ row }) => <VText value={row.reject_reason} line={3} />,
      },
    },

    {
      title: "备注信息",
      width: 180,
      slots: {
        default: ({ row }) => <VText value={row.remark} line={3} />,
      },
    },
    {
      title: "操作",
      width: 100,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              {row.operator_review_status == 1 ? (
                <div>
                  {/* <el-button link type="primary" onClick={() => onOperatorReview("CONFIRMED", row)}>
                    运营通过
                  </el-button>
                  <br />
                  <el-button link type="primary" onClick={() => onOperatorReview("REJECTED", row)}>
                    运营驳回
                  </el-button> */}

                  <VButton auth="/pmc/plan/unconfirmed/confirmed" link type="primary" onClick={() => onOperatorReview("CONFIRMED", row)}>
                    运营通过
                  </VButton>
                  <VButton auth="/pmc/plan/unconfirmed/rejected" link type="primary" onClick={() => onOperatorReview("REJECTED", row)}>
                    运营驳回
                  </VButton>
                </div>
              ) : (
                ""
              )}

              {row.operator_review_status == 0 || row.operator_review_status == 3 ? (
                <span>
                  {/* <el-button link type="primary" onClick={() => openConfirmInput("edit", row)}>
                    修改
                  </el-button> */}
                  <VButton auth="/pmc/plan/unconfirmed/batchUpdate" link type="primary" onClick={() => openConfirmInput("edit", row)}>
                    修改
                  </VButton>

                  {/* <el-button link type="primary" onClick={() => onOperatorReview("SUBMIT", row)}>
                    提交
                  </el-button> */}

                  <VButton auth="/pmc/plan/unconfirmed/submit" link type="primary" onClick={() => onOperatorReview("SUBMIT", row)}>
                    提交
                  </VButton>

                  <br />
                  {/* <el-button link type="danger" onClick={() => onOperatorReview("CANCEL", row)} class="mr-[12px]">
                    作废
                  </el-button> */}
                  <VButton auth="/pmc/plan/unconfirmed/cancel" link type="danger" onClick={() => onOperatorReview("CANCEL", row)}>
                    作废
                  </VButton>
                </span>
              ) : (
                ""
              )}
              {row.operator_review_status == 2 ? (
                <span>
                  {/* <el-button link type="danger" onClick={() => onOperatorReview("ROLLBACK", row)} class="mr-[12px]">
                    反审
                  </el-button> */}
                  <VButton auth="/pmc/plan/unconfirmed/rollback" link type="danger" onClick={() => onOperatorReview("ROLLBACK", row)}>
                    反审
                  </VButton>
                </span>
              ) : (
                ""
              )}
              <el-button link type="primary" onClick={() => logRef?.value.open({ spa_id: row?.spa_analysis?.spa_id })}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        form.operator_review_status = activeName.value
        let params = {
          ...initForm(form),
          page: page.pageNum,
          page_size: page.pageSize,
        }
        return queryList(params)
      },
    },
  },
})
const initForm = (form) => {
  let keys = ["plan_no", "sku", "asin"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
    form[key] = form[key]?.map((v) => v.trim())
  })
  return form
}

const queryList = async (params) => {
  let statusData = await reviewStatusStatistics({ ...params, operator_review_status: "" })
  statusOpt.value = statusData.data
  let res = await unconfirmedList(params)

  return res
}

const activityColor = {
  新品: "text-green",
  重点: "text-red",
}
</script>
<style lang="scss" scoped>
:deep(.view-table) {
}
</style>
<style lang="scss">
.my-message {
  max-width: 620px !important;
}
</style>
